﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.Data;
using VAdvantage.DataBase;
using VAdvantage.Grids;
using VAdvantage.Panels;
using VAdvantage.Utility;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using VAdvantage.Controls;
using System.Collections;
using VAdvantage.Print;
using VAdvantage.Model;
using System.Text;
using VAdvantage.Classes;
using System.Windows.Controls.DataVisualization.Charting;
using SL4PopupMenu;

namespace VAdvantage.Apps
{
    public partial class FramePaneView : CFrame, IBusy
    {

        /** MWindow for AccountCombination  */
        private GridWindow _mWindow = null;
        /** MTab for AccountCombination     */
        private GridTab _mTab = null;
        /** GridController                  */
        private GridController _gridController = null;
        /** Window No					*/
        private int _windowNo= 420420;

        BusyIndicator gridBusy = new BusyIndicator();
        BusyIndicator tabBusy = new BusyIndicator();

     //   private int _windowNo 

        public FramePaneView(bool b)
            : base("RoleCenter")
        {
            
        }

        public FramePaneView()
            : base("RoleCenter")
        {
            InitializeComponent();
            //LayoutGrid.Visibility = System.Windows.Visibility.Collapsed;

            gridBusy.Style = Application.Current.Resources["RoundBusyIndicator"] as Style;
            tabBusy.Style = Application.Current.Resources["RoundBusyIndicator"] as Style;

            label1.Content = Msg.GetMsg("Action");
            tabBusy.IsBusy = true;
            leftPanel.Child = tabBusy;

            gridBusy.IsBusy = true;
            Grid.SetColumn(gridBusy, 1);
            Grid.SetRow(gridBusy, 1);
            LayoutRoot.Children.Add(gridBusy);

           // _windowNo = Envs.CreateWindowNo(this);
            CreateInfoBar();
            LoadPanes();
            //LoadGrids();
        }

        int rcviewid = 0;
        string name = "";
        int colspan = 0;
        int rowspan = 0;
        int seqno = 0;
        int minvalue = 0;
        int maxvalue = 0;

        int bgcolorid = 0;
        int headercolorid = 0;
        int headerfontcolorid = 0;
        int fontcolorid = 0;
        int tabid = 0;
        int userqueryid = 0;
        int kpipaneid = 0;

        void LoadPanes()
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                LoadTabs();
                LoadGrids();
                //LoadGrids();

            });
        }

        List<MChart> listMChart = new List<MChart>();
        List<int> listKPIPaneID = new List<int>();

        List<GridController> listGrid = new List<GridController>();
        List<VGridPanel> listGridPanel = new List<VGridPanel>();
        List<VDataGrid> listDataGrid = new List<VDataGrid>();
        List<BusyIndicator> listBusy = new List<BusyIndicator>();
        List<int> listRCViewID = new List<int>();

        void LocatePanelOnGrid(GridController _gridController, MChart chart, string header, int KPI_ID)
        {
            LayoutGrid.ShowGridLines = false;
            bool isFirst = false;
            if (LayoutGrid.Children.Count == 0)
                isFirst = true;

            if (rowspan > 2)
                rowspan = 2;

            if (colspan > 3)
                colspan = 3;

            if (isFirst)
            {
                for (int r = 1; r <= rowspan; r++)
                    LayoutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                for (int c = 1; c <= colspan; c++)
                    LayoutGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });

                VGridPanel panel = new VGridPanel(rolecenter, false);
                //VDataGrid vTable = new VDataGrid();
                AddControl(panel, 0, 0, rowspan, colspan);

                //BusyIndicator busy = new BusyIndicator();
                //busy.Height = 60;
                //busy.Width = 80;
                //busy.BusyContent = "";
                //busy.IsBusy = true;
                //panel.AddControl(busy);

                panel.SetHeader(header);
                panel.SetGridController(_gridController);
                panel.SetScrollPanel(scrollPanels);

                if (chart != null)
                    panel.SetD_Chart_ID(chart.Get_ID());
                else if (_gridController != null)
                    panel.SetRC_View_ID(rcviewid);
                else
                    panel.SetKPI_Pane_ID(KPI_ID);

                panel.SetListTab(tabList);

                //listBusy.Add(busy);
                //listDataGrid.Add(vTable);
                listGridPanel.Add(panel);
                listMChart.Add(chart);
                listKPIPaneID.Add(KPI_ID);
                listRCViewID.Add(rcviewid);

                //_gridController.GetDataGrid(panel, vTable, busy, LayoutGrid, 0, 10, false);
                //panel.PanelData(vTable);

            }
            else
            {

                bool startNewRow = false;   //flag to see if the new row is to be created (only if colspan == 3)
                if (colspan == 3)
                    startNewRow = true;

                int colCount = LayoutGrid.ColumnDefinitions.Count;
                int rowCount = LayoutGrid.RowDefinitions.Count;
                if (colCount < 3)
                {
                    int c = colCount;
                    //check how many columns to be added
                    int colstoadd = 3 - c;  //3 is max
                    //if colspan + colstoadd < 3, it means we do not have to create full columns (other wise space will be left out)
                    if (colspan + c < 3)
                        colstoadd = colspan;
                    do
                    {
                        ColumnDefinition newColumn = new ColumnDefinition();
                        newColumn.Width = new GridLength(1, GridUnitType.Star);
                        LayoutGrid.ColumnDefinitions.Add(newColumn);
                        c++;
                    } while (c <= colstoadd);
                }

                if (startNewRow)
                {
                    int rownum = LayoutGrid.RowDefinitions.Count;
                    for (int r = 1; r <= rowspan; r++)
                        LayoutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });

                    VGridPanel panel = new VGridPanel(rolecenter, false);
                    //VDataGrid vTable = new VDataGrid();
                    AddControl(panel, rownum, 0, 1, colspan);
                    panel.SetScrollPanel(scrollPanels);
                    //BusyIndicator busy = new BusyIndicator();
                    //busy.Height = 60;
                    //busy.Width = 80;
                    //busy.BusyContent = "";
                    //busy.IsBusy = true;
                    //panel.AddControl(busy);
                    panel.SetHeader(header);
                    panel.SetGridController(_gridController);

                    if (chart != null)
                        panel.SetD_Chart_ID(chart.Get_ID());
                    else if (_gridController != null)
                        panel.SetRC_View_ID(rcviewid);
                    else
                        panel.SetKPI_Pane_ID(KPI_ID);
                    panel.SetListTab(tabList);

                    //listBusy.Add(busy);
                    //listDataGrid.Add(vTable);
                    listGridPanel.Add(panel);
                    listMChart.Add(chart);
                    listKPIPaneID.Add(KPI_ID);
                    listRCViewID.Add(rcviewid);
                    //_gridController.GetDataGrid(panel, vTable, busy, LayoutGrid, 0, 10, false);
                    //panel.PanelData(vTable);
                    return; //do nothing after this;
                }

                bool adjusted = true;   //represents if the panel has been adjusted between existing rows

                for (int r = 0; r < LayoutGrid.RowDefinitions.Count; r++)
                {
                    adjusted = false;
                    int colSapce = 0;
                    int currentCol = 0;

                    foreach (FrameworkElement rect in LayoutGrid.Children)
                    {
                        if (rect is BusyIndicator)
                            continue;

                        int rectrspan = Grid.GetRowSpan(rect);
                        if (Grid.GetRow(rect) != r)
                            continue;

                        //check if the requested rowspanning does not intersect with already exisiting panels
                        //if condition is not continued
                        colSapce += Grid.GetColumnSpan(rect);
                        currentCol = Grid.GetColumn(rect);

                        if (colSapce >= 3)
                            break;
                    }

                    if ((colSapce < 3) && ((3 - colSapce) >= colspan))   //if colspace is < 3, means panel has a place to be adjusted
                    {
                        //check previous row for any rowspanning to this row
                        //if (r > 0)
                        {
                            bool firstColAbove = false;
                            bool secondColAbove = false;
                            bool thirdColAbove = false;

                            bool freeAbove = true;
                            bool freeBelow = true;

                            //we will insert panel into r
                            foreach (FrameworkElement rect in LayoutGrid.Children)
                            {

                                int row = Grid.GetRow(rect);
                                if (row == (r - 1)) //check on above
                                {
                                    FrameworkElement element = GridExtensions.FindElement(LayoutGrid, row, 0);
                                    if (Grid.GetColumnSpan(element) >= 3)
                                    {
                                        freeAbove = true;
                                        break;
                                    }
                                    FrameworkElement elementN = GridExtensions.FindElement(LayoutGrid, r, 0);
                                    if (element != null && elementN == null)
                                    {
                                        if (Grid.GetRowSpan(element) > 1)
                                        {
                                            firstColAbove = false;
                                            //freeAbove = false;
                                            colSapce++;
                                        }
                                        else
                                            firstColAbove = true;
                                    }

                                    element = GridExtensions.FindElement(LayoutGrid, row, 1);
                                    elementN = GridExtensions.FindElement(LayoutGrid, r, 1);
                                    if (element != null && elementN == null)
                                    {
                                        if (Grid.GetRowSpan(element) > 1)
                                        {
                                            secondColAbove = false;
                                            //freeAbove = false;
                                            colSapce++;
                                        }
                                        else
                                            secondColAbove = true;
                                    }

                                    element = GridExtensions.FindElement(LayoutGrid, row, 2);
                                    elementN = GridExtensions.FindElement(LayoutGrid, r, 2);
                                    if (element != null && elementN == null)
                                    {
                                        if (Grid.GetRowSpan(element) > 1)
                                        {
                                            thirdColAbove = false;
                                            //freeAbove = false;
                                        }
                                        else
                                            thirdColAbove = true;
                                    }

                                    if (firstColAbove || secondColAbove || thirdColAbove)
                                        freeAbove = true;
                                    else
                                        freeAbove = false;

                                    break;

                                }
                            }


                            foreach (FrameworkElement rect in LayoutGrid.Children)
                            {
                                int row = Grid.GetRow(rect);
                                if (rowCount > r)
                                {
                                    if (row == (r + 1))
                                    {
                                        FrameworkElement element = GridExtensions.FindElement(LayoutGrid, row, colSapce);
                                        if (element != null)
                                        {
                                            if (Grid.GetColumnSpan(element) >= (3 - colSapce))
                                            {
                                                freeBelow = false;
                                                break;
                                            }
                                        }

                                        element = GridExtensions.FindElement(LayoutGrid, row, 1);
                                        if (element != null)
                                        {
                                            if (Grid.GetColumnSpan(element) >= 2)
                                            {
                                                freeBelow = false;
                                                break;
                                            }
                                        }

                                        element = GridExtensions.FindElement(LayoutGrid, row, 2);
                                        if (element != null)
                                        {
                                            freeBelow = false;
                                            break;
                                        }


                                        break;
                                    }
                                }

                            }

                            if (rowspan == 1)
                                freeBelow = true;

                            if (freeBelow && freeAbove)
                            {
                                if (LayoutGrid.RowDefinitions.Count < (r + rowspan))
                                    LayoutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });

                                VGridPanel panel = new VGridPanel(rolecenter, false);
                                AddControl(panel, r, colSapce, rowspan, colspan);
                                panel.SetScrollPanel(scrollPanels);
                                //BusyIndicator busy = new BusyIndicator();
                                //busy.Height = 60;
                                //busy.Width = 80;
                                //busy.BusyContent = "";
                                //busy.IsBusy = true;
                                //panel.AddControl(busy);
                                panel.SetHeader(header);
                                panel.SetGridController(_gridController);

                                if (chart != null)
                                    panel.SetD_Chart_ID(chart.Get_ID());
                                else if (_gridController != null)
                                    panel.SetRC_View_ID(rcviewid);
                                else
                                    panel.SetKPI_Pane_ID(KPI_ID);

                                panel.SetListTab(tabList);



                                //listBusy.Add(busy);
                                listGridPanel.Add(panel);
                                listMChart.Add(chart);
                                listKPIPaneID.Add(KPI_ID);
                                listRCViewID.Add(rcviewid);
                                //_gridController.GetDataGrid(panel, vTable, busy, LayoutGrid, 0, 10, false);
                                //panel.PanelData(vTable);

                                adjusted = true;

                                break;
                            }
                        }
                    }
                }

                if (!adjusted)
                {
                    for (int r = 1; r <= rowspan; r++)
                        LayoutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });

                    VGridPanel panel = new VGridPanel(rolecenter, false);
                    AddControl(panel, rowCount, 0, 1, colspan);
                    panel.SetScrollPanel(scrollPanels);
                    //BusyIndicator busy = new BusyIndicator();
                    //busy.Height = 60;
                    //busy.Width = 80;
                    //busy.BusyContent = "";
                    //busy.IsBusy = true;
                    //panel.AddControl(busy);
                    panel.SetHeader(header);
                    panel.SetGridController(_gridController);

                    if (chart != null)
                        panel.SetD_Chart_ID(chart.Get_ID());
                    else if (_gridController != null)
                        panel.SetRC_View_ID(rcviewid);
                    else
                        panel.SetKPI_Pane_ID(KPI_ID);
                    panel.SetListTab(tabList);


                    //listBusy.Add(busy);
                    listGridPanel.Add(panel);
                    listMChart.Add(chart);
                    listKPIPaneID.Add(KPI_ID);
                    listRCViewID.Add(rcviewid);
                    //_gridController.GetDataGrid(panel, vTable, busy, LayoutGrid, 0, 10, false);
                    //panel.PanelData(vTable);
                }
            }

        }

        void AddControl(FrameworkElement elem, int row, int col, int rowspan, int colspan)
        {
            Grid.SetRow(elem, row);
            Grid.SetColumn(elem, col);
            Grid.SetRowSpan(elem, rowspan);
            Grid.SetColumnSpan(elem, colspan);

            if (elem is VDataGrid)
            {


                VDataGrid grid = (elem as VDataGrid);
                //grid.MaxHeight = 250 * rowspan;
                grid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                grid.Padding = new Thickness(3, 15, 3, 15);


            }

            if (elem is VGridPanel)
            {
                //Border border = new Border();
                //border.BorderThickness = new Thickness(1);
                //border.BorderBrush = new SolidColorBrush(Colors.Black);
                //LayoutGrid.Children.Add(border);

                VGridPanel grid = (elem as VGridPanel);
                LayoutGrid.Height = (220 * LayoutGrid.RowDefinitions.Count) + (6 * LayoutGrid.RowDefinitions.Count);
                LayoutGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                grid.MaxHeight = 220 * rowspan;
                grid.MinHeight = 220 * rowspan;
                grid.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                grid.Margin = new Thickness(3, 3, 3, 3);

                //border.Child = grid;
            }

            if (elem is BusyIndicator)
            {
                LayoutGrid.Children.Add(elem);
            }

            LayoutGrid.Children.Add(elem);
        }

        void AddRow()
        {
            LayoutGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(220, GridUnitType.Pixel) });
        }

        void LoadGrids()
        {
            Dispatcher.BeginInvoke(delegate
            {
                //LayoutGrid.Visibility = System.Windows.Visibility.Visible;
                //gridBusy.Visibility = System.Windows.Visibility.Collapsed;

                tabBusy.IsBusy = false;
                gridBusy.IsBusy = false;

                TreeView tvLeft = new TreeView();
                tvLeft.Background = new SolidColorBrush(Colors.Transparent);
                tvLeft.BorderThickness = new Thickness(0);
                leftPanel.Child = tvLeft;

                ATreeViewItem header1 = new ATreeViewItem();
                header1.Margin = new Thickness(-10, -5, 0, 0);
                header1.Header = Msg.GetMsg(roleCenterName);
                base.Title = Msg.GetMsg(roleCenterName);
                header1.FontWeight = FontWeights.SemiBold;
                header1.Foreground = new SolidColorBrush(Colors.Black);
                header1.IsExpanded = true;
                header1.FontSize = 12;
                tvLeft.Items.Add(header1);

                for (int i = 0; i < lstTabName.Count; i++)
                {
                    try
                    {
                        ATreeViewItem items = new ATreeViewItem();
                        items.Header = lstTabName[i];
                        items.Tag = lstTabID[i];
                        byte[] data = (lstMImage[i] as MImage).GetBinaryData();
                        if (data != null)
                            items.Icon = (lstMImage[i] as MImage).GetImage();
                        else
                            items.Icon = Envs.LoadImageSource("DefaultWindow.png");
                        items.MouseLeftButtonUp += new MouseButtonEventHandler(item_MouseLeftButtonUp);
                        header1.Items.Add(items);
                    }
                    catch
                    {
                    }
                }

            });
        }

        int CurrentActiveID = 0;
        HashMap<int, Grid> ActiveGrids = new HashMap<int, Grid>();
        Grid LayoutGrid = null;
        ATreeViewItem item = null;
        int itemSelectedIndex = 0;

        void item_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

            item = (sender as ATreeViewItem);
            int id = (int)item.Tag;

            if (id.Equals(CurrentActiveID))
                return;

            byte[] data = (lstMImage[lstTabID.IndexOf(id)] as MImage).GetBinaryData();
            if (data != null)
                imgHeader.Source = (lstMImage[lstTabID.IndexOf(id)] as MImage).GetImage();
            else
                imgHeader.Source = Envs.LoadImageSource("DefaultWindow.png");

            lblHeader.Content = lstTabName[lstTabID.IndexOf(id)];


            gridBusy.Style = Application.Current.Resources["RoundBusyIndicator"] as Style;
            gridBusy.IsBusy = true;
            gridBusy.BusyContent = "Creating Layout...Please Wait";


            Grid OldGrid = ActiveGrids.Get(CurrentActiveID);
            Grid cachedGrid = ActiveGrids.Get(id);
            if (OldGrid != null)
            {
                scrollPanels.Content = null;
            }

            if (cachedGrid != null)
            {
                scrollPanels.Content = cachedGrid;
                gridBusy.IsBusy = false;
                CurrentActiveID = id;
                return;
            }

            for (int i = 0; i <= listGrid.Count - 1; i++)
            {
                GridController grid = listGrid[i];

                VGridPanel panel = listGridPanel[i];
                //panel.RemoveData();
            }

            //<Grid Margin="3,0,3,3" Name="LayoutGrid" ShowGridLines="False" Background="White" HorizontalAlignment="Stretch">
            LayoutGrid = new Grid();

            if (ActiveGrids.Get(id) == null)
                ActiveGrids.Add(id, LayoutGrid);

            LayoutGrid.Margin = new Thickness(1, 0, 1, 1);
            scrollPanels.Content = LayoutGrid;

            //LayoutGrid.Children.Clear();
            //LayoutGrid.RowDefinitions.Clear();
            //LayoutGrid.ColumnDefinitions.Clear();

            CurrentActiveID = id;
            LoadTabPanels(id);
        }


        public Grid LoadGridData(int id, int _CurrentActiveID, BusyIndicator _gridBusy, ScrollViewer _scrollPanels, out bool iscached)
        {
            scrollPanels = _scrollPanels;
            iscached = false;
            gridBusy = _gridBusy;
            CurrentActiveID = _CurrentActiveID;
            if (id.Equals(CurrentActiveID))
                return null;

            Grid OldGrid = ActiveGrids.Get(CurrentActiveID);
            Grid cachedGrid = ActiveGrids.Get(id);
            if (OldGrid != null)
            {
                _scrollPanels.Content = null;
            }

            if (cachedGrid != null)
            {
                //_scrollPanels.Content = cachedGrid;
                gridBusy.IsBusy = false;
                CurrentActiveID = id;
                iscached = true;
                return cachedGrid;
            }

            for (int i = 0; i <= listGrid.Count - 1; i++)
            {
                GridController grid = listGrid[i];

                VGridPanel panel = listGridPanel[i];
                //panel.RemoveData();
            }

            //<Grid Margin="3,0,3,3" Name="LayoutGrid" ShowGridLines="False" Background="White" HorizontalAlignment="Stretch">
            LayoutGrid = new Grid();

            if (ActiveGrids.Get(id) == null)
                ActiveGrids.Add(id, LayoutGrid);

            LayoutGrid.Margin = new Thickness(1, 0, 1, 1);

            CurrentActiveID = id;
            return LayoutGrid;
        }

        List<String> lstTabName = new List<string>();
        List<int> lstTabID = new List<int>();
        List<MImage> lstMImage = new List<MImage>();
        List<KeyNamePair> tabList = new List<KeyNamePair>();
        string roleCenterName = "";
        void LoadTabs()
        {
            string sql = @"
                    SELECT rcm.Name,
                      rct.Name,
                      rct.AD_Image_ID, rct.RC_RoleCenterTab_ID
                    FROM rc_rolecentermanager rcm
                    INNER JOIN rc_rolecentertab rct
                    ON rcm.rc_rolecentermanager_id = rct.rc_rolecentermanager_id 
                    where rcm.IsActive = 'Y' AND rcm.ad_role_id = " + Envs.GetCtx().GetAD_Role_ID() + " order by rct.seqno";

            tabList.Clear();
            IDataReader dr = DB.ExecuteReader(sql);
            if (dr != null)
            {
                while (dr.Read())
                {
                    roleCenterName = dr["Name"].ToString();
                    tabList.Add(new KeyNamePair(int.Parse(dr["RC_RoleCenterTab_ID"].ToString()), dr[1].ToString()));
                    lstTabName.Add(dr[1].ToString());
                    lstTabID.Add(int.Parse(dr[3].ToString()));

                    int temp = 0;

                    if (!dr[2].ToString().Equals(""))
                        temp = int.Parse(dr[2].ToString());

                    MImage image = MImage.Get(Envs.GetCtx(), temp);
                    lstMImage.Add(image);
                }
                dr.Close();
            }

        }

        List<int> lstFrameInQuery = new List<int>();

        public void LoadTabPanels(int id)
        {
            ThreadPool.QueueUserWorkItem(delegate
            {
                LoadFrames(id);
            });
        }


        ViennaRoleCenter rolecenter = null;
        List<int> MaxValues = new List<int>();
        bool isKPI = false;
        string kpiDescription = "";

        void LoadFrames(int ID)
        {
            listMChart.Clear();
            listKPIPaneID.Clear();
            listGrid.Clear();
            listGridPanel.Clear();
            listDataGrid.Clear();
            listBusy.Clear();
            listRCViewID.Clear();
            MaxValues.Clear();

            string sql = @"SELECT rcpane.rc_view_id,
                          rcpane.name,
                          rcpane.colspan,
                          rcpane.rowspan,
                          panel.seqno,
                          rcpane.minvalue,
                          rcpane.maxvalue,  
                          rcpane.font_color_id,
                          rcpane.headerbg_color_id,
                          rcpane.headerfont_color_id,
                          rcpane.bg_color_id,
                          rcview.Ad_Tab_ID,
                          rcview.AD_UserQuery_ID,
                          rcpane.RC_ViewPane_id,
                          panel.rc_tabpanels_id,
                          rcview.record_id ParentKey  , 'N' as IsKPI, rcpane.name as Description
                        FROM rc_view rcview
                        INNER JOIN RC_ViewPane rcpane
                        ON rcview.rc_view_id = rcpane.rc_view_id INNER JOIN rc_tabpanels panel
                        ON rcpane.RC_ViewPane_id = panel.record_id
                        WHERE panel.IsActive = 'Y' AND panel.rc_rolecentertab_id = " + ID + @" and panel.rolecenterpanels=1 UNION
 
                        Select a.D_Chart_id, a.Name, b.Colspan, b.Rowspan, panel.seqno, 
                        0, 0, 0, 0, 0, 0, 0, 0, b.rc_chartpane_id, panel.rc_tabpanels_id, 0 , 'N', b.name as Description from d_chart a inner join rc_chartpane b on a.d_chart_id = b.d_chart_id 
                        INNER JOIN rc_tabpanels panel
                        on b.rc_chartpane_id = panel.record_id
                        where panel.IsActive = 'Y' AND panel.rc_rolecentertab_id = " + ID + @" and panel.rolecenterpanels=2 
                        And a.IsActive='Y' ";

            sql += @" UNION select 0, b.Name, panel.Colspan, panel.Rowspan, panel.seqno,
                        0, 0, 0, 0, 0, 0, 0, 0, b.rc_kpipane_id, panel.rc_tabpanels_id, 0, 'Y', b.Description as Description from rc_kpipane b
                        inner join rc_tabpanels panel on
                        b.rc_kpipane_id = panel.record_id
                        where panel.IsActive = 'Y' AND panel.rc_rolecentertab_id = " + ID + " and panel.rolecenterpanels= 3  ";

            sql += " order by 5";

            IDataReader dr = DB.ExecuteReader(sql);
            if (dr == null)
            {
                Dispatcher.BeginInvoke(delegate
                {
                    gridBusy.Visibility = System.Windows.Visibility.Collapsed;

                });

                Thread.Sleep(0);
                return;

            }

            bool hasPanels = false;
            while (dr.Read())
            {
                hasPanels = true;
                rolecenter = new ViennaRoleCenter();

                rcviewid = int.Parse(dr["rc_view_id"].ToString());
                kpipaneid = int.Parse(dr["RC_ViewPane_id"].ToString());
                name = dr["name"].ToString();
                colspan = int.Parse(dr["colspan"].ToString());
                rowspan = int.Parse(dr["rowspan"].ToString());
                seqno = int.Parse(dr["seqno"].ToString());
                minvalue = int.Parse(dr["minvalue"].ToString());
                maxvalue = int.Parse(dr["maxvalue"].ToString());

                //bgcolorid = int.Parse(dr["bg_color_id"].ToString());
                //headercolorid = int.Parse(dr["headerbg_color_id"].ToString());
                bgcolorid = 0;
                headercolorid = 0;
                //headerfontcolorid = int.Parse(dr["headerfont_color_id"].ToString());
                //fontcolorid = int.Parse(dr["font_color_id"].ToString());
                tabid = int.Parse(dr["AD_Tab_ID"].ToString());
                userqueryid = int.Parse(dr["AD_UserQuery_ID"].ToString());
                isKPI = dr["IsKPI"].ToString().Equals("Y");
                kpiDescription = dr["Description"].ToString();
                MaxValues.Add(maxvalue);

                rolecenter.TabPanel_ID = int.Parse(dr["rc_tabpanels_id"].ToString());

                rolecenter.SeqNo = seqno;
                rolecenter.Rowspan = rowspan;
                rolecenter.Colspan = colspan;
                rolecenter.ListTab = tabList;
                rolecenter.MinValue = minvalue;
                rolecenter.MaxValue = maxvalue;
                rolecenter.PanelName = name;
                rolecenter.BGColor_ID = bgcolorid;
                rolecenter.HeaderBGColor_ID = headercolorid;
                rolecenter.FontColor_ID = fontcolorid;
                rolecenter.AD_Tab_ID = tabid;
                rolecenter.ADUserQuery_ID = userqueryid;
                rolecenter.RC_Tab_ID = CurrentActiveID;
                rolecenter.KPIPaneID = kpipaneid;
                rolecenter.IsKPI = isKPI;

                if (!dr["ParentKey"].ToString().Equals(""))
                    rolecenter.ParentKeyID = int.Parse(dr["ParentKey"].ToString());

                if (tabid > 0 && !isKPI)
                {
                    rolecenter.RC_View_ID = rcviewid;
                    rolecenter.FramePane_ID = int.Parse(dr["RC_ViewPane_id"].ToString());

                    List<int> visibleFields = new List<int>();
                    try
                    {
                        sql = "Select AD_Field_ID from RC_ViewColumn where IsActive = 'Y' and RC_View_ID = " + rcviewid;
                        IDataReader ndr = DB.ExecuteReader(sql, null);
                        while (ndr.Read())
                        {
                            if (ndr["AD_Field_ID"] != null)
                                visibleFields.Add(int.Parse(ndr["AD_Field_ID"].ToString()));
                        }
                    }
                    catch
                    {
                    }

                    MTab tab = MTab.Get(Envs.GetCtx(), tabid);

                    int AD_Window_ID = tab.GetAD_Window_ID();
                    GridWindowVO wVO = AEnv.GetMWindowVO(_windowNo, AD_Window_ID, 0);
                     wVO._isThroughRoleCenter = true;
                    if (wVO == null)
                    {
                        //do something.
                    }


                    _mWindow = new GridWindow(wVO);
                    _mTab = _mWindow.GetTabByID(tabid);

                    GridField[] findFields = _mTab.GetFields();
                    MUserQuery obj = new MUserQuery(Envs.GetContext(), userqueryid, null);
                    DataSet ds = obj.GetQueryLines();
                    Query _query = GetQueryAdvanced(ds, _mTab.GetTableName(), findFields);
                    if (_mTab.IsDetail())
                    {
                        _query.AddRestriction(_mTab.GetLinkColumnName(), "=", rolecenter.ParentKeyID);
                    }
                    _mTab.SetQuery(_query);

                    for (int i = 0; i < _mTab.GetFieldCount(); i++)
                    {
                        GridField field = _mTab.GetField(i);
                        if (!visibleFields.Contains(field.GetAD_Field_ID()))      //  check context
                        {
                            field.SetDisplayed(false);
                        }
                        //field.SetDisplayed(false);
                    }

                    bool isbusy = false;
                    //create controls

                    Dispatcher.BeginInvoke(delegate
                    {
                        //  GridController
                        _gridController = new GridController(false, true);
                        _gridController.InitGrid(_mTab, true, _windowNo, null, null);
                        _gridController.RegisterIBusy(this);

                        listGrid.Add(_gridController);
                        //IList _bs = _gridController.GetDataSource();
                        //_gridController.query(0, 3, false);

                        LocatePanelOnGrid(_gridController, null, name, 0);

                        //LayoutGrid.Layout = layout;
                        isbusy = true;

                    });

                    while (!isbusy)
                        Thread.Sleep(0);

                    isbusy = false;
                }
                else
                {
                    if (!isKPI) //CHART
                    {
                        rolecenter.D_Chart_ID = rcviewid;
                        rolecenter.ChartPane_ID = int.Parse(dr["RC_ViewPane_id"].ToString());

                        MChart chart = MChart.Get(rcviewid);
                        //listMChart.Add(chart);
                        bool isbusy = false;
                        Dispatcher.BeginInvoke(delegate
                        {
                            listGrid.Add(null);
                            LocatePanelOnGrid(null, chart, chart.GetName(), 0);
                            isbusy = true;
                        });

                        while (!isbusy)
                            Thread.Sleep(0);

                        isbusy = false;
                    }
                    else //KPI
                    {
                        rolecenter.Description = kpiDescription;
                        bool isbusy = false;
                        Dispatcher.BeginInvoke(delegate
                        {
                            listGrid.Add(null);
                            LocatePanelOnGrid(null, null, name, kpipaneid);
                            isbusy = true;
                        });

                        while (!isbusy)
                            Thread.Sleep(0);
                    }
                }
            }
            dr.Close();

            if (!hasPanels)
            {
                Dispatcher.BeginInvoke(delegate
                {
                    TextBlock nopanel = new TextBlock();
                    nopanel.Text = Msg.GetMsg("NoPanelAvail");


                    nopanel.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    nopanel.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;


                    Grid.SetRow(nopanel, 0);
                    Grid.SetColumn(nopanel, 0);

                    LayoutGrid.Children.Add(nopanel);
                    gridBusy.IsBusy = false;
                });
            }
            else
            {

                //finally load the grid controller
                Dispatcher.BeginInvoke(delegate
                {
                    gridBusy.IsBusy = false;
                    for (int i = 0; i <= listGrid.Count - 1; i++)
                    {
                        try
                        {
                            VGridPanel panel = listGridPanel[i];
                            panel.Visibility = System.Windows.Visibility.Visible;
                            if (listGrid[i] != null)   //Grid Window
                            {

                                GridController grid = listGrid[i];
                                grid.GetDataGrid(panel, LayoutGrid, 0, MaxValues[i], false, listRCViewID[i], true);
                            }
                            else if (listMChart[i] != null)  //CHART
                            {
                                panel.SetRootLayoutGrid(LayoutGrid);
                                panel.AddChart(listMChart[i]);
                            }
                            else  //KPI
                            {
                                panel.SetRootLayoutGrid(LayoutGrid);
                                panel.ADdKPI(listKPIPaneID[i]);
                            }
                        }
                        catch 
                        { 
                        }

                        //panel.PanelData(LayoutGrid);
                    }
                });
            }
        }


        private GridField GetTargetMField(GridField[] _findFields, string columnName)
        {
            // if no column name, then return null
            if (columnName == null)
                return null;
            // else find field for the given column
            for (int c = 0; c < _findFields.Length; c++)
            {
                GridField field = _findFields[c];
                if (columnName.Equals(field.GetColumnName()))
                    return field;
            }
            return null;
        }


        private Object ParseValue(GridField field, object pp)
        {
            if (pp == null)
                return null;
            int dt = field.GetDisplayType();
            String inStr = pp.ToString();
            if (inStr == null || inStr.Equals(Null.NULLString) || inStr == "")
                return null;
            try
            {
                //	Return Integer
                if (dt == DisplayType.Integer
                    || (DisplayType.IsID(dt) && field.GetColumnName().EndsWith("_ID")))
                {
                    int i = int.Parse(inStr);
                    return i;
                }
                //	Return BigDecimal
                else if (DisplayType.IsNumeric(dt))
                {
                    return Decimal.Parse(inStr);       //DisplayType.GetNumberFormat(dt).GetFormatedValue(inStr);
                }
                //	Return Timestamp
                else if (DisplayType.IsDate(dt))
                {
                    String time = "";
                    try
                    {
                        return DateTime.Parse(inStr);
                    }
                    catch (Exception e)
                    {
                        //log.Log(Level.WARNING, inStr + "(" + inStr.GetType().FullName + ")" + e);
                        time = DisplayType.GetDateFormat(dt).Format(inStr);
                    }
                    try
                    {
                        return DateTime.Parse(time);
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                //log.Log(Level.WARNING, "Object=" + inStr, ex);
                String error = ex.Message;
                if (error == null || error.Length == 0)
                    error = ex.ToString();
                StringBuilder errMsg = new StringBuilder();
                errMsg.Append(field.GetColumnName()).Append(" = ").Append(inStr).Append(" - ").Append(error);
                //
                ShowMessage.Error("ValidationError", true, errMsg.ToString());
                return null;
            }

            return inStr;
        }	//	parseValue

        private Query GetQueryAdvanced(DataSet dsAdvanceData, String _tableName, GridField[] gridField)
        {
            Query query = new Query(_tableName);
            // check if dataset have any table
            if (dsAdvanceData.Tables.Count == 1)
            {
                // for every row in dataset
                for (int i = 0; i < dsAdvanceData.Tables[0].Rows.Count; i++)
                {
                    DataRow dtRowObj = dsAdvanceData.Tables[0].Rows[i];
                    //	Column
                    string infoName = dtRowObj["KEYNAME"].ToString();
                    string columnName = dtRowObj["KEYVALUE"].ToString();
                    GridField field = GetTargetMField(gridField, columnName);
                    string columnSQL = field.GetColumnSQL(); //
                    //	Operator
                    string optr = dtRowObj["OPERATORNAME"].ToString(); //dtRowObj["OPERATOR"].ToString()
                    //	Value

                    object value = dtRowObj["VALUE1VALUE"];

                    object parsedValue = null;
                    if (value != null && value.ToString().Trim().StartsWith("adddays") || value.ToString().Trim().StartsWith("@"))
                    {
                        ;
                    }
                    else
                    {
                        parsedValue = ParseValue(field, value);
                    }

                    //string infoDisplay = dtRowObj["VALUE1NAME"].ToString();
                    String infoDisplay = null;

                    if (value == null || value.ToString().Length < 1)
                    {
                        if (Query.BETWEEN.Equals(optr))
                            continue;	//	no null in between
                        parsedValue = Null.NULLString;
                        infoDisplay = "NULL";
                    }
                    else
                    {
                        infoDisplay = dtRowObj["VALUE1NAME"].ToString();
                    }

                    //	Value2
                    // if "BETWEEN" selected
                    if (Query.BETWEEN.Equals(optr))
                    {

                        object value2 = dtRowObj["VALUE2VALUE"].ToString();
                        if (value2 == null || value2.ToString().Trim().Length < 1)
                            continue;

                        Object parsedValue2 = ParseValue(field, value2);
                        string infoDisplay_to = dtRowObj["VALUE2NAME"].ToString();
                        if (parsedValue2 == null)
                            continue;
                        // else add restriction where clause to query with between operator
                        query.AddRangeRestriction(columnSQL, parsedValue, parsedValue2, infoName,
                            infoDisplay, infoDisplay_to);
                    }
                    else
                    {
                        if (parsedValue == null && value != null && (value.ToString().Trim().StartsWith("adddays") || value.ToString().Trim().StartsWith("@")))
                        {
                            string Where = columnName + optr + value;
                            Where = Envs.ParseContext(Envs.GetCtx(), 0, Where, false);
                            query.AddRestriction(Where);
                        }
                        else
                        {
                            query.AddRestriction(columnSQL, optr, parsedValue, infoName, infoDisplay);
                        }
                    }
                }
            }
            return query;
        }


        /// <summary>
        /// Cretae Info Window's items
        /// </summary>
        private void CreateInfoBar()
        {

            PopupMenu infoWin = new PopupMenu();

            PopupMenuItem mnu = new PopupMenuItem("Images/AddFrameX32.png", Msg.GetMsg(Envs.GetCtx(), Msg.GetMsg("AddView")), null);
            mnu.Name = "AddView";
            //mnu.Click += new RoutedEventHandler(mnu_Click);
            infoWin.AddItem(mnu);

            mnu = new PopupMenuItem("Images/AddChartX32.png", Msg.GetMsg(Envs.GetCtx(), Msg.GetMsg("AddChart")), null);
            mnu.Name = "AddChart";
            //mnu.Click += new RoutedEventHandler(mnuChart_Click);
            infoWin.Items.Add(mnu);

            mnu = new PopupMenuItem("Images/AddChartX32.png", Msg.GetMsg(Envs.GetCtx(), Msg.GetMsg("AddKPI")), null);
            mnu.Name = "AddKPIPane";
            //mnu.Click += new RoutedEventHandler(mnuKPI_Click);
            infoWin.Items.Add(mnu);

            infoWin.AddSeparator();

            mnu = new PopupMenuItem("Images/ResetCacheX32.png", Msg.GetMsg(Envs.GetCtx(), Msg.GetMsg("ResetCache")), null);
            mnu.Name = "ResetCache";
            //mnu.Click += new RoutedEventHandler(mnuResetCahce_Click);
            infoWin.Items.Add(mnu);

            infoWin.AddTrigger(TriggerTypes.LeftClick, image1);
            infoWin.AddTrigger(TriggerTypes.LeftClick, label1);
        }

        public void AddTabToList(List<KeyNamePair> keys)
        {
            tabList = keys;
        }

        public void AddChart()
        {
            ViennaRoleCenter rc = new ViennaRoleCenter();
            rc.ListTab = tabList;
            rc.RC_Tab_ID = CurrentActiveID;
            AddChartToTab addFrame = new AddChartToTab(rc);
            //Utility.Envs.RegisterWindowForm(addFrame);
            addFrame.Left = 330;
            addFrame.Top = 120;
            
            addFrame.Show();
        }


        public void AddKPI()
        {
            ViennaRoleCenter rc = new ViennaRoleCenter();
            rc.ListTab = tabList;
            rc.RC_Tab_ID = CurrentActiveID;

            KPIPane addFrame = new KPIPane(rc);
           //Utility.Envs.RegisterWindowForm(addFrame);
            addFrame.Left = 330;
            addFrame.Top = 120;
            addFrame.Show();
          //  Envs.ShowForm(addFrame);
        }


        public void Reset()
        {
            ActiveGrids.Remove(CurrentActiveID);
            CurrentActiveID = 0;

            if(scrollPanels != null)
                scrollPanels.Content = null;

            if(imgHeader != null)
                imgHeader.Source = null;

            if(lblHeader != null)
                lblHeader.Content = "";

            ShowMessage.Info("ResetDone", false, "", "");

            if (item != null)
                item_MouseLeftButtonUp(item, null);
        }

        public void AddFrame()
        {
            ViennaRoleCenter rc = new ViennaRoleCenter();
            rc.ListTab = tabList;
            rc.RC_Tab_ID = CurrentActiveID;

            FramePane addFrame = new FramePane(rc);
            Utility.Envs.RegisterWindowForm(addFrame);
            addFrame.Left = 330;
            addFrame.Top = 120;
            addFrame.Show();
        }


        void mnuChart_Click(object sender, RoutedEventArgs e)
        {
            ViennaRoleCenter rc = new ViennaRoleCenter();
            rc.ListTab = tabList;
            AddChartToTab addFrame = new AddChartToTab(rc);
            //Utility.Envs.RegisterWindowForm(addFrame);
            addFrame.Show();
        }

        void mnu_Click(object sender, RoutedEventArgs e)
        {
            ViennaRoleCenter rc = new ViennaRoleCenter();
            rc.ListTab = tabList;
            FramePane addFrame = new FramePane(rc);
            Utility.Envs.RegisterWindowForm(addFrame);
            addFrame.Show();
        }
        #region IBusy Members

        public void SetBusy(bool isbusy)
        {
            this.Cursor = isbusy ? Cursors.Wait : Cursors.Arrow;
        }

        #endregion

        private void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        private void image1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            CreateInfoBar();
        }


    }

    public static class GridExtensions
    {
        public static FrameworkElement FindElement(this Grid instance, int row, int col)
        {
            FrameworkElement returnFE = null;
            if (null == instance)
            {
                throw new ArgumentNullException("instance");
            }
            List<FrameworkElement> list = new List<FrameworkElement>();
            foreach (FrameworkElement fe in instance.Children)
            {
                if (Grid.GetRow(fe) == row && Grid.GetColumn(fe) == col)
                {
                    if (fe is BusyIndicator)
                        continue;
                    returnFE = fe;
                    break;
                }
            }

            return returnFE;
        }
    }
}
